package cn.liontalk.service.impl;

import cn.liontalk.common.redis.RedisService;
import cn.liontalk.common.redis.prefix.MiaoShaKey;
import cn.liontalk.common.redis.prefix.UserKey;
import cn.liontalk.common.result.CodeMsg;
import cn.liontalk.controller.LoginController;
import cn.liontalk.dao.UserDao;
import cn.liontalk.entity.User;
import cn.liontalk.exception.GlobalException;
import cn.liontalk.service.UserService;
import cn.liontalk.util.MD5Util;
import cn.liontalk.util.UUIDutil;
import cn.liontalk.vo.LoginVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: 周哲
 * @package: cn.liontalk.service.impl
 * @description:
 * @date: 2019/1/18 15:34
 * @version: V1.0
 */
@Service
public class UserServiceImpl implements UserService {


    private static Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    public static final String COOK_NAME_TOKEN = "token";

    @Autowired
    private UserDao userDao;


    @Autowired
    private UserService userService;


    @Autowired
    private RedisService redisService;

    /**
     * 根据ID 查询用户
     *
     * @param id 用户ID
     * @return 用户信息
     */
    @Override
    public User getUserById(String id) {
        User user = redisService.get(UserKey.getById, id, User.class);
        if (null != user) {
            return user;
        }
        user = userDao.getUserById(id);
        if (null == user) {
            log.error("User Not Exist !!!");
            throw new GlobalException(CodeMsg.USER_NOT_EXIST);
        }
        redisService.set(UserKey.getById, id  , user);
        return user;
    }


    /**
     * 更新用户密码
     * @param token token
     * @param id 用户ID
     * @param newPassword 用户新密码
     * @return 是否操作成功
     */
    public boolean updateUserPassword(String token,Long id,String newPassword){
        User user = getUserById(String.valueOf(id));
        if(user==null){
            throw new GlobalException(CodeMsg.USER_NOT_EXIST);
        }

        String password = (MD5Util.formInputPassWord(newPassword,user.getSalt()));
        userDao.updateUserPassword(id,password);

        redisService.del(UserKey.getById,String.valueOf(user.getId()));
        user.setPassword(password);
        redisService.set(MiaoShaKey.TOKEN,token,user);
        return true;
    }



    /**
     * 增加用户
     *
     * @return 返回影响行数
     */

    @Override
    public int insertUser() {
        return insert();
    }

    /**
     * 用户登录
     *
     * @param loginVO 用户登录信息实体
     * @return 返回登录用户
     */
    @Override
    public String login(HttpServletResponse response, LoginVO loginVO) {
        if (null == loginVO) {
            throw new GlobalException(CodeMsg.SERVER_ERROR);
        }
        String mobile = loginVO.getMobile();
        String fromPass = loginVO.getPassword();
        User user = userService.getUserById(mobile);
        if (null == user) {
            throw new GlobalException(CodeMsg.USER_NOT_EXIST);
        }
        String dbPassword = user.getPassword();
        String dbSalt = user.getSalt();
        String result = MD5Util.formInputPassWord(fromPass, dbSalt);
        if (!result.equals(dbPassword)) {
            throw new GlobalException(CodeMsg.PASSWORD_ERROR);
        }
        String token = UUIDutil.getUUID();
        addCookie(response, token, user);
        return token;
    }

    /**
     * 根据token 获取用户信息
     *
     * @param token token
     * @return User 用户信息
     */
    @Override
    public User getUserByToken(HttpServletResponse response, String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        User user = redisService.get(MiaoShaKey.TOKEN, token, User.class);
        if (user != null) {
            addCookie(response, token, user);
        }
        return user;
    }


    @Transactional(rollbackFor = Exception.class)
    public  int insert() {
        User user = new User();
        user.setId(1);

        User users = new User();
        userDao.insertUser(user);
        return userDao.insertUser(users);
    }


    private void addCookie(HttpServletResponse response, String token, User user) {
        redisService.set(MiaoShaKey.TOKEN, token, user);
        Cookie cookie = new Cookie(COOK_NAME_TOKEN, token);
        cookie.setMaxAge(MiaoShaKey.TOKEN.expireSeconds());
        cookie.setPath("/");
        response.addCookie(cookie);

    }

}
